package com.tbit.uqbike.webmanager.controller;

import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.UserAuthWhiteList;
import com.tbit.uqbike.object.pojo.dto.UserAuthWhiteListDTO;
import com.tbit.uqbike.object.pojo.vo.UserAuthWhiteListVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.UserAuthWhiteListService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.ExportExcelUtils;
import com.tbit.uqbike.webmanager.util.csv.annotations.AsyncDownload;
import com.tbit.uqbike.webmanager.util.csv.entity.DownloadDTO;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 身份认证白名单
 */
@Slf4j
@RestController
@RequestMapping("/userAuthWhiteList")
public class UserAuthWhiteListController  extends BaseController {

    @Autowired
    private UserAuthWhiteListService userAuthWhiteListService;
    @Autowired
    private AccountService accountService;




    /**
     * 分页查询
     * @param authNo 证件号
     * @param name  证件归属人姓名
     * @param pageSize 每页行数
     * @param pageIndex 当前页数
     * @return
     */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(Integer brandId, String authNo, String name, @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(defaultValue = "1") Integer pageIndex, Date startTime, Date endTime, HttpServletRequest request){
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        /*if (!loginInfo.type.equals(UserConstant.USER_ADMIN) && !loginInfo.type.equals(UserConstant.USER_BRAND) && !loginInfo.type.equals(UserConstant.USER_FRANCHISEE)) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }*/
        if (loginInfo.type.equals(UserConstant.USER_BRAND)) {
            brandId = loginInfo.id;
        } else if (loginInfo.type.equals(UserConstant.USER_FRANCHISEE)) {
            brandId = accountService.getBrandId(loginInfo.id);
        } /*else {
            Assert.notNull(brandId, "ver.accountId.notNull");
        }*/
        PageResult<UserAuthWhiteListDTO> pageResult = userAuthWhiteListService.queryPage(brandId, authNo, name, pageSize, pageIndex, startTime, endTime);
        return JsonResult.ok(pageResult);
    }


    /**
     * 学生认证白名单导出
     * @return fileName
     */
    @GetMapping("/exportAuthWhiteList")
    public Result<Object> exportAuthWhiteList(Integer brandId, String authNo, String name, Date startTime, Date endTime, HttpServletRequest request) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        /*if (!loginInfo.type.equals(UserConstant.USER_ADMIN) && !loginInfo.type.equals(UserConstant.USER_BRAND) && !loginInfo.type.equals(UserConstant.USER_FRANCHISEE)) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }*/
        if (loginInfo.type.equals(UserConstant.USER_BRAND)) {
            brandId = loginInfo.id;
        } else if (loginInfo.type.equals(UserConstant.USER_FRANCHISEE)) {
            brandId = accountService.getBrandId(loginInfo.id);
        } /*else {
            Assert.notNull(brandId, "ver.accountId.notNull");
        }*/
        PageResult<UserAuthWhiteListDTO> pageResult = userAuthWhiteListService.queryPage(brandId, authNo, name, 1, 65535, startTime, endTime);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = String.format("%s~%s 退款记录", sdf.format(startTime), sdf.format(endTime));
        ExcelUtil<UserAuthWhiteListDTO> excelUtil = new ExcelUtil<>(UserAuthWhiteListDTO.class);
        JsonResult result = excelUtil.exportExcel(pageResult.getList(), fileName);
        return Result.success(result.getData());
    }


    /**
     * 新增/修改，传id修改，不传id新增
     * @param vo
     * @return
     */
    @RequestMapping("/update")
    public JsonResult update(@Valid UserAuthWhiteListVO vo, HttpServletRequest request){
        LoginInfo loginInfo = getLogin(request);
        Integer accountUserId = loginInfo.getAccountUserId();
        Integer brandId = vo.getBrandId();
        /*if (!loginInfo.type.equals(UserConstant.USER_ADMIN) && !loginInfo.type.equals(UserConstant.USER_BRAND)
                && !loginInfo.type.equals(UserConstant.USER_FRANCHISEE) && !loginInfo.type.equals(UserConstant.USER_AGENT)) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }*/
        if (loginInfo.type.equals(UserConstant.USER_BRAND)) {
            brandId = loginInfo.id;
        } else if (loginInfo.type.equals(UserConstant.USER_FRANCHISEE)) {
            brandId = accountService.getBrandId(loginInfo.id);
        } /*else {
            Assert.notNull(brandId, "ver.accountId.notNull");
        }*/
        vo.setBrandId(brandId);
        userAuthWhiteListService.update(vo, accountUserId);
        return JsonResult.ok();
    }

    /**
     * 删除
     * @param id 数据id
     * @param request
     * @return
     */
    @OperateLog(module = ModuleEnum.AUTH_WHITE_LIST, methods = MethodEnum.AUTH_WHITE_LIST_DEL)
    @RequestMapping("/del")
    public JsonResult del(@NotNull Integer id, HttpServletRequest request){
        /*LoginInfo loginInfo = getLogin(request);
        if (!loginInfo.type.equals(UserConstant.USER_ADMIN) && !loginInfo.type.equals(UserConstant.USER_BRAND) && !loginInfo.type.equals(UserConstant.USER_FRANCHISEE)
                && !loginInfo.type.equals(UserConstant.USER_AGENT)) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }*/
        userAuthWhiteListService.del(id);
        return JsonResult.ok();
    }

    /**
     * 导入数据
     * @param brandId 品牌id
     * @param file 模板文件
     * @param request
     * @return
     */
    @RequestMapping("/importData")
    public JsonResult importData(@NotNull(message = "ver.accountId.notNull") Integer brandId, @RequestParam("file") MultipartFile[] files,
                                 HttpServletRequest request, Integer override){
        LoginInfo loginInfo = getLogin(request);
        Integer accountUserId = loginInfo.getAccountUserId();
        List<UserAuthWhiteList> info = getInfo(files, 1, brandId, accountUserId);
        if(info.size() > 1000){
            throw new BaseException(SystemCodeEnum.AUTH_UPLOAD_SIZE_LIMIT);
        }
        if(override == null){
            override = 0;
        }
        userAuthWhiteListService.batchUpdate(info, override);

        return JsonResult.ok();
    }

    /**
     * 导入重复数据检查
     * @param brandId 品牌id
     * @param file 文件
     * @param request
     * @return
     */
    @RequestMapping("/importCheck")
    public JsonResult importCheck(@NotNull(message = "ver.accountId.notNull") Integer brandId, @RequestParam("file") MultipartFile[] files,
                                  HttpServletRequest request){
        LoginInfo loginInfo = getLogin(request);
        Integer accountUserId = loginInfo.getAccountUserId();
        List<UserAuthWhiteList> info = getInfo(files, 1, brandId, accountUserId);
        if(info.size() > 1000){
            throw new BaseException(SystemCodeEnum.AUTH_UPLOAD_SIZE_LIMIT);
        }
        List<String> existNo = userAuthWhiteListService.importCheck(info);
        if(CollectionUtils.isEmpty(existNo)){
            return JsonResult.ok("");
        }
        return JsonResult.ok(existNo.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }

    public List<UserAuthWhiteList> getInfo(MultipartFile[] files, Integer type, Integer brandId, Integer accountUserId) {
        if (null == files || files.length == 0) {
            throw new BaseException(SystemCodeEnum.HAVE_NOT_FILE);
        }
        List<List<String>> data = null;
        try {
            data = ExportExcelUtils.readExcelDataFirst(files[0].getBytes(), type);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        if (null == data) {
            throw new BaseException(SystemCodeEnum.READ_FILE_ERROR);
        }
        List<UserAuthWhiteList> list = new ArrayList<>();
        for (List<String> datum : data) {
            String authNo = datum.get(0);
            String capacity = datum.get(1);
            String name = datum.get(2);
            String authType = datum.get(3);
            if(!org.springframework.util.StringUtils.hasLength(authNo)){
                throw new BaseException(SystemCodeEnum.AUTH_NO_MUST_NOT_NULL);
            }
            if(!org.springframework.util.StringUtils.hasLength(capacity)){
                throw new BaseException(SystemCodeEnum.AUTH_CAPACITY_MUST_NOT_NULL);
            }
            UserAuthWhiteList userAuthWhiteListVO = new UserAuthWhiteList();
            userAuthWhiteListVO.setBrandId(brandId);
            userAuthWhiteListVO.setAuthNo(authNo);
            userAuthWhiteListVO.setType(authType);
            userAuthWhiteListVO.setName(name);
            userAuthWhiteListVO.setCapacity(Integer.parseInt(capacity));
            userAuthWhiteListVO.setUpdateUserId(accountUserId);
            list.add(userAuthWhiteListVO);
        }
        if (CollectionUtils.isEmpty(list)) {
            throw new BaseException(SystemCodeEnum.COLL_IS_EMPTY);
        }
        return list;
    }

    /**
     * 导出模板
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportTemplate")
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response) {
        // 下载模板文件
        LoginInfo info = getLogin(request);
        String authNo = info.context.getMessage("auth.no");
        String capacity = info.context.getMessage("auth.capacity");
        String name = info.context.getMessage("auth.name");
        String type = info.context.getMessage("auth.type");
        List<String[]> listContent = new LinkedList<>();
        String[] headers = {authNo, capacity, name, type};
        listContent.add(headers);
        String[] items = new String[]{"123456789", "10", "张三", "工号"};
        listContent.add(items);
        ExportExcelWrapper<String[]> export = new ExportExcelWrapper<>();
        export.exportExcel("template", "template", null, listContent, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    /**
     * 证件白名单导出
     * @param downloadDTO 不填
     * @param brandId 品牌id
     * @param authNo 证件号
     * @param name 证件归属姓名
     * @return
     */
    @AsyncDownload(defaultFileName = "证件白名单")
    @RequestMapping(value = "/download")
    public Result download(DownloadDTO downloadDTO,Integer brandId, String authNo, String name, Date startTime, Date endTime){
        return Result.success(userAuthWhiteListService.download(brandId, authNo, name, startTime, endTime, downloadDTO));
    }
}
